In [2]:
from datetime import datetime

In [8]:
def get_earliest(date1, date2):
    try:
        d1 = datetime.strptime(date1, "%m/%d/%Y")
        d2 = datetime.strptime(date2, "%m/%d/%Y")
        return date1 if d1 < d2 else date2
    except ValueError:
        return min(date1, date2)

In [9]:
import unittest


class GetEarliestTests(unittest.TestCase):

    """Tests for get_earliest."""

    def test_same_month_and_day(self):
        newer = "01/27/1832"
        older = "01/27/1756"
        self.assertEqual(get_earliest(newer, older), older)

    def test_february_29th(self):
        newer = "02/29/1972"
        older = "12/21/1946"
        self.assertEqual(get_earliest(newer, older), older)

    def test_smaller_month_bigger_day(self):
        newer = "03/21/1946"
        older = "02/24/1946"
        self.assertEqual(get_earliest(older, newer), older)

    def test_same_month_and_year(self):
        newer = "06/24/1958"
        older = "06/21/1958"
        self.assertEqual(get_earliest(older, newer), older)

    def test_invalid_date_allowed(self):
        newer = "02/29/2006"
        older = "02/28/2006"
        self.assertEqual(get_earliest(older, newer), older)

    def test_two_invalid_dates(self):
        newer = "02/30/2006"
        older = "02/29/2006"
        self.assertEqual(get_earliest(newer, older), older)

    def test_two_invalid_dates_v2(self):
        newer = "01/32/2007"
        older = "02/29/2006"
        self.assertEqual(get_earliest(newer, older), older)     

if __name__ == "__main__":
    unittest.main(argv=['first-arg-is-ignored'], exit=False)


......F
======================================================================
FAIL: test_two_invalid_dates_v2 (__main__.GetEarliestTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython-input-9-584db24a3933>", line 41, in test_two_invalid_dates_v2
    self.assertEqual(get_earliest(newer, older), older)
AssertionError: '01/32/2007' != '02/29/2006'
- 01/32/2007
+ 02/29/2006


----------------------------------------------------------------------
Ran 7 tests in 0.004s

FAILED (failures=1)

The above solution does not work for the unittest 'test_two_invalid_dates_v2'. In the solution, min() just looks at the smallest string lexicographically i.e using ASCII value of the characters. So 01 get is lexicographically smaller than 02, eventhough 02/29/2006 is older than 01/32/2007


In [ ]: